<template>
  <common-layout>
    <div class="top">
      <!-- <img alt="logo" class="logo" :src="logoUrl" /> -->
      <div class="title">
        <div class="name">{{ systemName }}</div>
        <div class="desc">
          {{ descText }}
        </div>
      </div>
    </div>
    <div class="login">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        @submit="onSubmit"
      >
        <a-alert
          class="mb20"
          type="error"
          v-if="isError"
          :message="messageError"
          showIcon
        />
        <a-form-model-item prop="account">
          <a-input
            v-model.trim="form.account"
            size="large"
            placeholder="请输入手机号"
            :maxLength="11"
            @blur="onBlur"
          >
            <a-icon slot="prefix" type="phone" />
          </a-input>
        </a-form-model-item>
        <div style="display: flex">
          <a-form-model-item prop="verificationCode">
            <a-input
              v-model.trim="form.verificationCode"
              size="large"
              placeholder="请输入验证码"
            >
            </a-input>
          </a-form-model-item>
          <a-form-model-item>
            <a-button
              type="primary"
              :disabled="!!count"
              class="captach-type"
              @click="onImgCaptcha"
            >
              {{ count ? `${count}s` : "获取验证码" }}
            </a-button>
          </a-form-model-item>
        </div>
        <a-form-model-item>
          <div style="mt20">
            <a-button
              :loading="logging"
              size="large"
              type="primary"
              class="login-button"
              :disabled="isLoading"
              htmlType="submit"
              >登录</a-button
            >
          </div>
        </a-form-model-item>
      </a-form-model>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from "@/layouts/CommonLayout.vue";
import Regex from "@/utils/regex.js";
import {
  login,
  getLoginCode,
  getToken,
  getIsAvailable,
  getEnterprise,
  getMenu
} from "@/services/user";
import { loadRoutes } from "@/utils/routerUtil";
import { setAuthorization } from "@/utils/request";
import {
  descText,
  ACCOUNT_TYPE_MAP,
  USER_TYPE_MAP,
  CLIENT_TYPE_MAP,
  CERTIFICATION_TYPE_MAP
} from "@/config/const";
import { mapMutations } from "vuex";
import { UC_URL } from "@/services/api";
const defaultPath = "/enterprise";

export default {
  name: "Login",
  components: { CommonLayout },
  data() {
    return {
      UC_URL,
      logoUrl: require("@/assets/img/logo.png"),
      descText,
      logging: false,
      isLoading: false,
      isCaptcha: false,
      captchaUrl: "",
      isError: false,
      messageError: "",
      form: {
        accountType: ACCOUNT_TYPE_MAP.phoneCode,
        clientType: CLIENT_TYPE_MAP.web,
        userType: USER_TYPE_MAP.outer, // internal:内部用户 outer:外部用户
        verificationCode: "",
        thirdUnionId: "",
        imgCode: "",
        account: "",
        password: ""
      },
      rules: {
        account: [
          {
            required: true,
            message: "请输入手机号",
            trigger: "blur"
          },
          {
            message: "请输入正确的手机号",
            trigger: "change",
            validator: this.onVerifiCertificatesPhone
          }
        ],
        verificationCode: [
          {
            required: true,
            message: "请输入验证码",
            trigger: "blur"
          },
          {
            message: "请输入正确的验证码",
            trigger: "change",
            validator: this.onVerificationCode
          }
        ]
      },
      count: 0,
      account: ""
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    }
  },
  mounted() {},
  destroyed() {
    clearInterval(this.interval);
  },
  methods: {
    ...mapMutations("account", [
      "setUser",
      "setPermissions",
      "setRoles",
      "setEnterpriseId",
      "setEnterpriseList",
      "setUserInfo"
    ]),
    // 账号输入框获取焦点
    onfocus(e) {
      this.account = e.target._value;
    },
    // 密码输入框失去焦点
    onBlur(e) {
      if (e.target._value !== this.account) {
        this.count = 0;
        clearInterval(this.interval);
        this.account = e.target._value;
      }
    },
    // 校验手机号
    onVerifiCertificatesPhone(rule, value) {
      return Regex.phone.test(value);
    },
    // 校验验证码
    onVerificationCode(rule, value) {
      return Regex.verificationCode.test(value);
    },
    // 滑块验证
    async onImgCaptcha() {
      if (this.form.account !== undefined && this.form.account.length > 0) {
        let verifyRes = await this.$ifCaptcha.verify({
          captchaGetUrl: `${UC_URL}/captcha/get`,
          captchaCheckUrl: `${UC_URL}/captcha/check`
        });
        if (verifyRes) {
          this.onCaptcha(verifyRes);
        } else {
          this.$message.warning("发送验证码失败: 安全验证未完成");
        }
      } else {
        this.$message.error("请输入手机号");
      }
    },
    // 获取验证码
    onCaptcha(verifyRes) {
      let params = {
        account: this.form.account,
        accountType: ACCOUNT_TYPE_MAP.phoneCode,
        cerificationType: CERTIFICATION_TYPE_MAP.login,
        ...verifyRes
      };
      this.onGetCheckCode(params);
    },
    // 获取验证码
    onGetCheckCode(params) {
      this.$refs.ruleForm.validateField("account", async (err) => {
        if (!err) {
          const {
            data: { code, message, data }
          } = await getLoginCode(params);
          if (code === 200) {
            this.form.verificationCode = data?.smsCode || '';
            this.count = 59;
            this.interval = setInterval(() => {
              if (this.count > 0) {
                this.count -= 1;
              } else if (this.count === 0) {
                clearInterval(this.interval);
              }
            }, 1000);
          } else {
            this.$message.warning(message);
          }
        }
      });
    },
    onSubmit(e) {
      e.preventDefault();
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.logging = true;
          let form = JSON.parse(JSON.stringify(this.form));
          login(form)
            .then(this.afterLogin)
            .finally(() => {
              this.logging = false;
            });
        } else {
          this.$message.error("请检查表单信息！");
        }
      });
    },
    afterLogin(res) {
      const loginRes = res.data;
      if (loginRes.success === 1) {
        // 保存token
        const { userCode } = loginRes.data;
        let tokenRes = {};
        let appId = window.__POWERED_BY_QIANKUN__
          ? this.$store.state.appId
          : process.env.VUE_APP_ID; // 平台id
        getToken({ userCode, appId, account: this.form.account }).then(
          (res) => {
            if (res.data.success) {
              tokenRes = res.data;
              setAuthorization({
                token: tokenRes.data.accessToken,
                openId: tokenRes.data.openId
              });
              this.getIsAvailable();
            }
          }
        );
      } else {
        this.count = 0;
        this.isError = true;
        this.messageError = loginRes.message;
      }
    },
    // 是否企业可用
    async getIsAvailable() {
      const {
        data: { code, message }
      } = await getIsAvailable();
      if (code === 200) {
        this.getEnterprise();
      } else if (code === 4000) {
        this.count = 0;
        this.$message.warning(message);
      }
    },
    // 判断企业个数是否大于1，如大于1则跳转至企业列表，等于1则直接跳到主页
    async getEnterprise() {
      const {
        data: {
          data: { enterprises },
          code
        }
      } = await getEnterprise();
      if (code === 200) {
        this.setEnterpriseList(enterprises || []);
        const enterpriseNum = 1;
        if (enterprises) {
          let hasLen = enterprises.length > enterpriseNum;
          if (hasLen) {
            this.$router.push(defaultPath);
            return;
          }
          let [{ id }] = enterprises;
          this.getMenu(id);
        } else {
          this.$message.error("未查到所属企业");
        }
      }
    },
    // 动态获取路由，跳转至路由第一个路径
    async getMenu(id) {
      setAuthorization(
        {
          enterpriseId: id
        },
        "basic"
      );
      this.setEnterpriseId(id);
      // 目前还不确定怎么将参数传递给前端，暂时传null
      let params = {
        departmentId: null,
        roleId: null
      };

      const {
        data: { data, code }
      } = await getMenu(params);
      if (code === 200) {
        const {
          username: user = "",
          permissions,
          roles = [],
          resources,
          departmentId,
          roleId,
          departmentName,
          roleName
        } = data;

        this.setUserInfo({ departmentName, roleName });
        setAuthorization(
          {
            departmentId,
            roleId
          },
          "auth1"
        );

        this.setUser(user);
        this.setPermissions(permissions || []);
        this.setRoles(roles);
        console.log(resources);
        if (!!resources && resources[0].children.length > 0) {
          loadRoutes(resources);
          this.$router.push("/home");
        } else {
          this.$message.warning("当前企业页面不存在");
        }
      }
    },
    onRedirectLogin() {
      const { VUE_APP_SSO_URL: path, VUE_APP_REDIRECT_URL: redirect_url } =
        process.env;
      let url = encodeURIComponent(`${redirect_url}/#/enterprise`);
      location.href = `${path}?mode=TOKEN&redirect_url=${url}`;
    }
  }
};
</script>

<style lang="less" scoped>
.common-layout {
  background-image: url("../../assets/img/bg.jpg");
  background-size: cover;
  background-position: center center;
  background-repeat: no-repeat;
  width: 100%;
  height: 100vh;

  .login {
    ::v-deep .ant-input {
      background: transparent;
      border-radius: 100px;
      height: 50px;
      line-height: 50px;
      color: #fff;
      caret-color: #fff;

      &:-internal-autofill-previewed,
      &:-internal-autofill-selected {
        -webkit-text-fill-color: #ffffff;
        -webkit-box-shadow: 0 0 0 100px #133844 inset !important;
        transition: background-color 5000s ease-in-out 0s;
      }
      &:hover {
        background-color: transparent;
      }
      &:focus {
        background-color: transparent;
      }
    }

    .anticon {
      color: #fff;
    }

    .login-button {
      width: 60%;
      margin-right: 36px;
      border-radius: 100px;
    }
  }

  ::v-deep .ant-input-password {
    &:hover {
      background-color: transparent;
    }
  }
  ::v-deep .ant-input-password-icon {
    color: #fff;
  }

  a {
    text-decoration: none;
    color: #fff;
  }
  .top {
    margin-bottom: 20px;
    display: flex;
    align-items: center;

    .logo {
      height: 70px;
      vertical-align: top;
      margin-right: 16px;
      @media screen and (max-width: 576px) {
        height: 50px;
      }
    }
    .title {
      .name {
        font-style: normal;
        font-weight: 700;
        font-size: 48px;
        line-height: 46px;
        color: #fff;
        @media screen and (max-width: 576px) {
          font-size: 20px;
          line-height: 20px;
        }
      }
      .desc {
        font-size: 14px;
        line-height: 18px;
        padding-top: 10px;
        color: #fff;
        @media screen and (max-width: 576px) {
          font-size: 10px;
        }
      }
    }
  }
  .login {
    width: 464px;
    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }
    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
    .captcha {
      display: inline-block;
      width: 120px;
      height: 40px;
      margin: auto 10px;
      line-height: 50px;
    }

    .captach-type {
      vertical-align: bottom;
      margin-left: 10px;

      &:disabled {
        color: #000;
      }
    }
  }
  ::v-deep .footer {
    width: 100%;
    position: fixed;
    color: #fff;
    bottom: 0;
    .copyright {
      color: #fff;
    }
    .links {
      display: none;
    }
  }
}
</style>
